DAY1:Create Phone Number


Posted by birdbirdmurmur on 2023-07-14

題目連結:Create Phone Number(6kyu)

解題思維:

1.用slice分割陣列,分成區域碼、第一段、第二段
2.使用join('')連結成字串
3.回傳

解法:

function createPhoneNumber(numbers){
  const areaCode = numbers.slice(0, 3).join('');
  const firstPart = numbers.slice(3, 6).join('');
  const secondPart = numbers.slice(6).join('');

  return `(${areaCode}) ${firstPart}-${secondPart}`
}

延伸思考:

  • join('')會將陣列裡的元素連結成字串 ex:[1,2,3] >>> 123
    • 若使用join(),元素和元素之間會多一個逗號(,) ex:[1,2,3] >>> 1,2,3

參考資料:


#javascript #Codewars #slice #join







Related Posts

D24_ ALG101-Unit 5

D24_ ALG101-Unit 5

2021 年末幾本有印象的書

2021 年末幾本有印象的書

使用Pagy製作Blog分頁(Ruby on Rails)

使用Pagy製作Blog分頁(Ruby on Rails)


Comments